package com.lmt.service;

import com.lmt.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import rx.Observable;
import rx.observers.Observers;

import java.util.HashMap;

/**
 * Date 2018/06/30
 *
 * @author MT-Lin
 */
@SuppressWarnings("deprecation")
@Service
public class AggregationService {

    private final RestTemplate restTemplate;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public AggregationService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @HystrixCommand(fallbackMethod = "fallback")
    public Observable<User> findUserByIdFromProvider(String id){
        logger.warn("gateway-zuul-aggregation->findUserByIdFromProvider:id={}", id);
        return Observable.create(observer -> {
            User user = restTemplate.getForObject("http://provider/findUserById?id={1}", User.class, id);
            observer.onNext(user);
            observer.onCompleted();
        });
    }

    @HystrixCommand(fallbackMethod = "fallback")
    public Observable<User> findUserByIdFromConsumer(String id){
        logger.warn("gateway-zuul-aggregation->findUserByIdFromConsumer:id={}", id);
        return Observable.create(observer -> {
            User user = restTemplate.getForObject("http://consumer/findUserById?id={1}", User.class, id);
            observer.onNext(user);
            observer.onCompleted();
        });
    }

    public User fallback(String id){
        return new User();
    }
}
